package com.stu.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stu.bean.Images;
import com.stu.service.ImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class ImagesController {
    @Autowired
    private ImagesService imagesService;

    @RequestMapping("/getImages")
    @ResponseBody
    public Object getAllImages(Images images, @RequestParam(value = "pageSize",required = false,defaultValue = "3") int pageSize, @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum){
        System.out.println(images);
        PageHelper.startPage(pageNum,pageSize);
        Page<Images> image = imagesService.selectImages(images);
        PageInfo<Images> pageInfo = new PageInfo<Images>(image,5);
        return pageInfo;
    }

    @RequestMapping(value= "/images/{imgId}",method = RequestMethod.DELETE)
    @ResponseBody
    public int getAllImages(@PathVariable("imgId") int imgId){
        System.out.println(imgId);
        return imagesService.deleteImages(imgId);
    }

    @RequestMapping("/insert")
    public String imgRegister(@Valid Images images, MultipartFile img, Model model, BindingResult bindingResult, HttpSession session) throws IOException {
        System.out.println(images);
        System.out.println(img);
        if(bindingResult.hasErrors()){
            Map<String,String> map = new HashMap<String, String>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(FieldError fieldError:fieldErrors){
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",map);
            return "home";
        }
        String imgPath = "c:/images/";
        String imgName = new Date().getTime()+img.getOriginalFilename();
        File file = new File(imgPath+imgName);
        img.transferTo(file);
        images.setImgurl("/images/"+imgName);

        Images insert = imagesService.insert(images);
        System.out.println(insert);
        if(insert!=null){
            session.setAttribute("insert",insert);
            return "home";
        }else{
            return "home";
        }
    }
}
